﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using BigDataFramework.Library.Objects;
using BigDataFramework.Helpers;
using System.Runtime.Serialization;
using BigDataFramework.Library.Objects.DataAdapters;
using BigDataFramework.Repositories;
using BigData.DataContracts.Objects;
using Igloo.SharpSquare.Entities;
using BigDataFramework.Library.Objects.DataAdapters.FourSquare;
using BigDataFramework.Repositories.Interfaces;
using BigData.DataContracts.Objects.BigData;
using MongoDB.Bson;
using BigDataFramework.Library.Helpers;
using BigData.DataContracts.Objects.FourSquare;
using MongoDB.Driver;
using BigDataFramework.Library.Objects.DataAdapters.Twitter;
using BigDataFramework.Library.Objects.DataAdapters.Reddit;
using BigData.DataContracts.Objects.Twitter;

namespace BigDataTester
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Test();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
        }

        public void Test()
        {
            PopulateTheDatabase();
            return;
            if (Environment.UserName.Contains("Alex"))
                AlexTest();
            else if (Environment.UserName.Contains("Mehdi"))
                MehdiTest();
            else if (Environment.UserName.ToLower().Contains("jason"))
                JasonTest();
            else if (Environment.UserName.Contains("singh"))
                HershTest();
        }

        private void AlexTest()
        {
            //PopulateTheDatabase();
            //return;

            MongoDBRepository dbContext = new MongoDBRepository();

            BigDataUser gilliganUser = dbContext.ReadOne<BigDataUser>(u => u.FirstName.Contains("Gil"));
            //List<RegisteredCollection> bos = dbContext.Read<RegisteredCollection>().ToList();
            //List<BigDataUserToRegisteredCollection> bob = dbContext.Read<BigDataUserToRegisteredCollection>(bdc => bdc.BigDataUserId == user).ToList();

            //bob.LastDataSync = DateTime.MinValue;

            //dbContext.Update(bob);

            #region To Lazy to comment... this is a unit of work
            //BigDataUser user = dbContext.ReadOne<BigDataUser>(usera => usera.FirstName.Contains("Gill"));
            //DataProvider provider = dbContext.ReadOne<DataProvider>(dp => dp.Name.Contains("Reddit"));

            //RegisteredCollection regColl = dbContext.ReadOne<RegisteredCollection>(rc => ObjectId.Parse(provider._id) == rc.DataProvider);
            //List<Event> events = dbContext.Read<Event>(e => e.RegisteredCollectionId == ObjectId.Parse(regColl._id)).ToList();
            //List<BigData.DataContracts.Objects.Reddit.Comment> comments = dbContext.Read<BigData.DataContracts.Objects.Reddit.Comment>().ToList();

            //BigDataUserToRegisteredCollection collection = dbContext.ReadOne<BigDataUserToRegisteredCollection>(rc =>
            //            rc.RegisteredCollectionId == ObjectId.Parse(regColl._id)
            //        &&  rc.BigDataUserId == ObjectId.Parse(user._id)
            //    );

            //collection.LastDataSync = DateTime.MinValue;

            //dbContext.Update(collection);

            //foreach (BigData.DataContracts.Objects.Reddit.Comment c in comments)
            //    dbContext.Delete(c);

            //foreach (Event e in events)
            //{
            //    dbContext.Delete(e);
            //} 
            #endregion

            Console.WriteLine();
        }

        private void MehdiTest()
        {
            //BigDataFramework.Library.Objects.DataAdapters.Reddit.SubmittedAdapter da = new BigDataFramework.Library.Objects.DataAdapters.Reddit.SubmittedAdapter(BigDataFramework.Library.Objects.DataAdapters.Reddit.RedditDataAdapterHelper.DefaultUserName, BigDataFramework.Library.Objects.DataAdapters.Reddit.RedditDataAdapterHelper.DefaultPassword);
            //List<BigData.DataContracts.Objects.Reddit.Link> hi = da.GetSubmitted(DateTime.Now.AddDays(-90), DateTime.Now);
            Console.WriteLine("");
        }

        private void JasonTest()
        {
            //PopulateTheDatabase();
        }

        private void HershTest()
        {
        }

        private void btnPullData_Click(object sender, EventArgs e)
        {
            // How to pull data for a specific person
            MongoDBRepository   dbContext;
            BigDataUser         user;

            dbContext   = new MongoDBRepository();

            // Pulling all of Gilligan's data
            user = dbContext.ReadOne<BigDataUser>(bdu =>
                        bdu.FirstName == "Gilligan"
                    &&  bdu.LastName == "Willoughby"

                    &&  bdu.RecordStartDate <= DateTime.Now
                    &&  bdu.RecordEndDate >= DateTime.Now
                );

            // Foursquare: Checkins
            DataAdapterBase<BigDataFourSquareCheckin> dataAdapter = new FourSquareDataAdapterCheckin();
            List<BigDataFourSquareCheckin> checkins;
            // Retrieving his checkins from the dataAdapter... which in turn pulls everything from the foursquare API
            checkins = dataAdapter.GetDataUpdatesSinceLastSync(
                        user: user
                    , shouldUpdateLastSyncDate: true
                );

            dbContext.Create(checkins);

            // REDDIT: Comments
            CommentsAdapter redditcommentAdapter = new CommentsAdapter();
            List<BigData.DataContracts.Objects.Reddit.Comment> comments = redditcommentAdapter.GetDataUpdatesSinceLastSync(
                        user: user
                    , shouldUpdateLastSyncDate: true
                );

            dbContext.Create(comments);

            // REDDIT: Link
            //DataAdapterBase<Disliked>

            // Twitter
            DataAdapterBase<BigDataTwitterTweet> twitterAdapter = new TwitterDataAdapter();
            List<BigDataTwitterTweet> tweets;
            // Retrieving his checkins from the dataAdapter... which in turn pulls everything from the foursquare API
            tweets = twitterAdapter.GetDataUpdatesSinceLastSync(
                        user: user
                    , shouldUpdateLastSyncDate: true
                );

            dbContext.Create(tweets);
            MessageBox.Show("Complete");
        }

        private void btnProcessEvents_Click(object sender, EventArgs e)
        {
            // How to convert the objects stored in the registered collections into events

            // Sync FourSquare checkins
            DataAdapterBase<BigDataFourSquareCheckin> dataAdapter = new FourSquareDataAdapterCheckin();
            dataAdapter.SyncDataToEvents();

            // Sync DataAdapter Comments
            DataAdapterBase<BigData.DataContracts.Objects.Reddit.Comment> commentAdapter = new CommentsAdapter();
            commentAdapter.SyncDataToEvents();

            // Sync Twitter Comments
            DataAdapterBase<BigData.DataContracts.Objects.Twitter.BigDataTwitterTweet> twitterAdapter = new TwitterDataAdapter();
            twitterAdapter.SyncDataToEvents();
            MessageBox.Show("Complete");
        }

        private void PopulateTheDatabase()
        {
            MongoDBRepository dbContext = new MongoDBRepository();

            BigDataUser gilligan = new BigDataUser()
            {
                FirstName = "Gilligan",
                LastName = "Willoughby",
                MiddleName = "J.",
                RecordStartDate = DateTime.Now,
                RecordEndDate = DateTime.MaxValue
            };

            BigDataUser mehdi = new BigDataUser()
            {
                FirstName = "Mehdi",
                LastName = "Sabroui",
                MiddleName = "",
                RecordStartDate = DateTime.Now,
                RecordEndDate = DateTime.MaxValue
            };

            BigDataUser jason = new BigDataUser()
            {
                FirstName = "Jason",
                LastName = "Eisenmenger",
                MiddleName = "",
                RecordStartDate = DateTime.Now,
                RecordEndDate = DateTime.MaxValue
            };

            dbContext.Create<BigDataUser>(new List<BigDataUser>() {
                gilligan,
                mehdi,
                jason
            });

            gilligan = dbContext.ReadOne<BigDataUser>(u => u.FirstName == gilligan.FirstName && u.LastName == gilligan.LastName && u.MiddleName == gilligan.MiddleName);
            mehdi = dbContext.ReadOne<BigDataUser>(u => u.FirstName == mehdi.FirstName && u.LastName == mehdi.LastName && u.MiddleName == mehdi.MiddleName);
            jason = dbContext.ReadOne<BigDataUser>(u => u.FirstName == jason.FirstName && u.LastName == jason.LastName && u.MiddleName == jason.MiddleName);

            DataProvider twitter = new DataProvider()
            {
                Name = "Twitter",
                Description = "",
                ApiDocumentationLink = new List<string>()
            };

            DataProvider foursquare = new DataProvider()
            {
                Name = "FourSquare",
                Description = "",
                ApiDocumentationLink = new List<string>() { @"https://developer.foursquare.com/" }
            };

            DataProvider reddit = new DataProvider()
            {
                Name = "Reddit",
                Description = "",
                ApiDocumentationLink = new List<string>()
            };

            DataProvider miscDataProvider = new DataProvider()
            {
                Name = "Test",
                Description = "The Data Provider to associate test data with",
                ApiDocumentationLink = new List<string>()
            };

            dbContext.Create(new List<DataProvider>() {
                twitter,
                foursquare,
                reddit,
                miscDataProvider
            });

            twitter = dbContext.ReadOne<DataProvider>(dp => dp.Name == twitter.Name);
            foursquare = dbContext.ReadOne<DataProvider>(dp => dp.Name == foursquare.Name);
            reddit = dbContext.ReadOne<DataProvider>(dp => dp.Name == reddit.Name);
            miscDataProvider = dbContext.ReadOne<DataProvider>(dp => dp.Name == miscDataProvider.Name);

            RegisteredCollection coll1 = new RegisteredCollection()
            {
                CollectionName = MongoDBRepositoryHelper.ConvertTypeToCollectionName(typeof(BigDataFourSquareCheckin)),
                ObjectTypeName = typeof(BigDataFourSquareCheckin).FullName,
                DataProvider = ObjectId.Parse(foursquare._id),
                RecordStartDate = DateTime.Now,
                RecordEndDate = DateTime.MaxValue
            };

            RegisteredCollection coll2 = new RegisteredCollection()
            {
                CollectionName = MongoDBRepositoryHelper.ConvertTypeToCollectionName(typeof(BigDataTestCollection)),
                ObjectTypeName = typeof(BigDataTestCollection).FullName,
                DataProvider = ObjectId.Parse(miscDataProvider._id),
                RecordStartDate = DateTime.Now,
                RecordEndDate = DateTime.MaxValue
            };

            RegisteredCollection coll3 = new RegisteredCollection()
            {
                CollectionName = MongoDBRepositoryHelper.ConvertTypeToCollectionName(typeof(BigData.DataContracts.Objects.Reddit.Comment)),
                ObjectTypeName = typeof(BigData.DataContracts.Objects.Reddit.Comment).FullName,
                DataProvider = ObjectId.Parse(reddit._id),
                RecordStartDate = DateTime.Now,
                RecordEndDate = DateTime.MaxValue
            };

            RegisteredCollection coll4 = new RegisteredCollection()
            {
                CollectionName = MongoDBRepositoryHelper.ConvertTypeToCollectionName(typeof(BigData.DataContracts.Objects.Twitter.BigDataTwitterTweet)),
                ObjectTypeName = typeof(BigData.DataContracts.Objects.Twitter.BigDataTwitterTweet).FullName,
                DataProvider = ObjectId.Parse(twitter._id),
                RecordStartDate = DateTime.Now,
                RecordEndDate = DateTime.MaxValue
            };

            MongoDBRepositoryHelper.AddRegisteredCollection(coll1);
            MongoDBRepositoryHelper.AddRegisteredCollection(coll2);
            MongoDBRepositoryHelper.AddRegisteredCollection(coll3);
            MongoDBRepositoryHelper.AddRegisteredCollection(coll4);

            coll1 = dbContext.ReadOne<RegisteredCollection>(rc => rc.CollectionName == coll1.CollectionName);
            coll2 = dbContext.ReadOne<RegisteredCollection>(rc => rc.CollectionName == coll2.CollectionName);
            coll3 = dbContext.ReadOne<RegisteredCollection>(rc => rc.CollectionName == coll3.CollectionName);
            coll4 = dbContext.ReadOne<RegisteredCollection>(rc => rc.CollectionName == coll4.CollectionName);

            BigDataUserToRegisteredCollection gilliganBDUTRC = new BigDataUserToRegisteredCollection()
            {
                BigDataUserId = ObjectId.Parse(gilligan._id),
                LastDataSync = DateTime.MinValue,
                RegisteredCollectionId = ObjectId.Parse(coll2._id),
                RecordStartDate = DateTime.Now,
                RecordEndDate = DateTime.MaxValue
            };

            BigDataUserToRegisteredCollection gilliganBDUTRC_twitter = new BigDataUserToRegisteredCollection()
            {
                BigDataUserId = ObjectId.Parse(gilligan._id),
                LastDataSync = DateTime.MinValue,
                RegisteredCollectionId = ObjectId.Parse(coll4._id),
                RecordStartDate = DateTime.Now,
                RecordEndDate = DateTime.MaxValue
            };

            BigDataUserToRegisteredCollection mehdiBDUTRC = new BigDataUserToRegisteredCollection()
            {
                BigDataUserId = ObjectId.Parse(mehdi._id),
                LastDataSync = DateTime.MinValue,
                RegisteredCollectionId = ObjectId.Parse(coll2._id),
                RecordStartDate = DateTime.Now,
                RecordEndDate = DateTime.MaxValue
            };

            BigDataUserToRegisteredCollection jasonBDUTRC = new BigDataUserToRegisteredCollection()
            {
                BigDataUserId = ObjectId.Parse(jason._id),
                LastDataSync = DateTime.MinValue,
                RegisteredCollectionId = ObjectId.Parse(coll2._id),
                RecordStartDate = DateTime.Now,
                RecordEndDate = DateTime.MaxValue
            };

            BigDataUserToRegisteredCollection gilliganBDUTRC_reddit = new BigDataUserToRegisteredCollection()
            {
                BigDataUserId = ObjectId.Parse(gilligan._id),
                LastDataSync = DateTime.MinValue,
                RegisteredCollectionId = ObjectId.Parse(coll3._id),
                RecordStartDate = DateTime.Now,
                RecordEndDate = DateTime.MaxValue
            };

            dbContext.Create(new List<BigDataUserToRegisteredCollection>() {
                gilliganBDUTRC,
                mehdiBDUTRC,
                jasonBDUTRC,
                gilliganBDUTRC_reddit,
                gilliganBDUTRC_twitter
            });

            gilliganBDUTRC = dbContext.ReadOne<BigDataUserToRegisteredCollection>(rc => rc.BigDataUserId == gilliganBDUTRC.BigDataUserId && rc.RegisteredCollectionId == gilliganBDUTRC.RegisteredCollectionId);
            mehdiBDUTRC = dbContext.ReadOne<BigDataUserToRegisteredCollection>(rc => rc.BigDataUserId == mehdiBDUTRC.BigDataUserId && rc.RegisteredCollectionId == mehdiBDUTRC.RegisteredCollectionId);
            jasonBDUTRC = dbContext.ReadOne<BigDataUserToRegisteredCollection>(rc => rc.BigDataUserId == jasonBDUTRC.BigDataUserId && rc.RegisteredCollectionId == jasonBDUTRC.RegisteredCollectionId);
            gilliganBDUTRC_reddit = dbContext.ReadOne<BigDataUserToRegisteredCollection>(rc => rc.BigDataUserId == gilliganBDUTRC_reddit.BigDataUserId && rc.RegisteredCollectionId == gilliganBDUTRC_reddit.RegisteredCollectionId);
            gilliganBDUTRC_twitter = dbContext.ReadOne<BigDataUserToRegisteredCollection>(rc => rc.BigDataUserId == gilliganBDUTRC_twitter.BigDataUserId && rc.RegisteredCollectionId == gilliganBDUTRC_twitter.RegisteredCollectionId);

            Event event1 = new Event()
            {
                AffiliatedUserIds = new List<ObjectId>() { ObjectId.Parse(gilligan._id), ObjectId.Parse(jason._id), ObjectId.Parse(mehdi._id) },
                EndDate = DateTime.Today.AddDays(2),
                Headline = "Super Amazing Wagon Adventure",
                Media = new EventMedia()
                {
                    Caption = "It's amazing... you could even call it... \"Super Amazing\"",
                    Credit = "sparsevector",
                    URL = @"http://www.youtube.com/watch?v=AkT-kfgwbZQ"
                },
                RecordEndDate = DateTime.MaxValue,
                RecordStartDate = DateTime.Now,
                RegisteredCollectionId = ObjectId.Parse(coll2._id),
                RegisteredCollectionObjectId = ObjectId.Empty,
                StartDate = DateTime.Today.AddDays(-20),
                Text = "Gilligan, Mehdi, and Jason spent many a day trying to beat the epicness that was \"Super Amazing Wagon Adventure\""
            };

            Event event2 = new Event()
            {
                AffiliatedUserIds = new List<ObjectId>() { ObjectId.Parse(gilligan._id), ObjectId.Parse(jason._id), ObjectId.Parse(mehdi._id) },
                EndDate = DateTime.Today.AddMinutes(60),
                Headline = "Kitty Kitty Playtime!!!!",
                Media = new EventMedia()
                {
                    Caption = "Kitty!!!!!",
                    Credit = "www.shockblast.net",
                    URL = @"http://img.becomegorgeous.com/user/2/7/8/5/kitty_maci/photos/my_fav_/cute_kitty-1245.jpg"
                },
                RecordEndDate = DateTime.MaxValue,
                RecordStartDate = DateTime.Now,
                RegisteredCollectionId = ObjectId.Parse(coll2._id),
                RegisteredCollectionObjectId = ObjectId.Empty,
                StartDate = DateTime.Today,
                Text = "Mehdi managed to convince both Gilligan and Jason to play with the kitties"
            };

            Event event3 = new Event()
            {
                AffiliatedUserIds = new List<ObjectId>() { ObjectId.Parse(gilligan._id) },
                EndDate = DateTime.Today.AddDays(3).AddMinutes(30),
                Headline = "Taking a break",
                Media = new EventMedia()
                {
                    Caption = "Ladies and Gentleman!!! I present to you the Appletini!!!",
                    Credit = @"http://youcandrinkthis.blogspot.com/2011/06/you-can-drink-this-appletini.html",
                    URL = @"http://3.bp.blogspot.com/-4eet302MzH4/TfVZJ-TTZOI/AAAAAAAAADg/zXKeHHWA1C0/s1600/appletini.jpg"
                },
                RecordEndDate = DateTime.MaxValue,
                RecordStartDate = DateTime.Now,
                RegisteredCollectionId = ObjectId.Parse(coll2._id),
                RegisteredCollectionObjectId = ObjectId.Empty,
                StartDate = DateTime.Today.AddDays(3),
                Text = @"Gilligan decided it was high time to take a break and drink his favorite drink... the appletini. Instructions for making them are here http://youcandrinkthis.blogspot.com/2011/06/you-can-drink-this-appletini.html, in case you wish to make your own"
            };

            dbContext.Create(new List<Event>() { event1, event2, event3 });

            BigDataUserToRedditUserData gilliganRedditUser = new BigDataUserToRedditUserData()
            {
                BigDataUserId = ObjectId.Parse(gilligan._id),
                RedditUserId = "GilliganWilloughby",
                RedditUserPassword = "Skipper5!", // This will need to be encrypted at some point (it's just not right now)
                RecordStartDate = DateTime.Now,
                RecordEndDate = DateTime.MaxValue
            };

            dbContext.Create<BigDataUserToRedditUserData>(gilliganRedditUser);

            gilliganRedditUser = dbContext.ReadOne<BigDataUserToRedditUserData>(bdutrud => bdutrud.BigDataUserId == gilliganRedditUser.BigDataUserId && bdutrud.RedditUserId == gilliganRedditUser.RedditUserId && bdutrud.RedditUserPassword == gilliganRedditUser.RedditUserPassword);

            MessageBox.Show("Database Add complete");
        }
    }
}
